#pragma once
#include <esent.h>
#include "Instance.h"
namespace ese {
	class session
	{
	public:

		session() = delete;
		session(const session&) = delete;
		session(session&&) = delete;

		session(ese::jet& v) : m_ese(v)
			, m_jses(JET_sesidNil)
			, m_last_error(JET_errSuccess) {}

		~session(){ try { stop(); } catch (...) {} }

		const JET_SESID id(){ return m_jses; }
		const JET_ERR last_error(void) const { return m_last_error; }
		const ese::jet& ese() const { return m_ese; }

		bool start();
		bool stop();

		bool begin_transaction() { return JET_errSuccess == (m_last_error = JetBeginTransaction(m_jses)); }
		bool commit(JET_GRBIT grbit = JET_bitCommitLazyFlush) { return JET_errSuccess == (m_last_error = JetCommitTransaction(m_jses, grbit)); }
		bool rollback(JET_GRBIT grbit = JET_bitRollbackAll) { return JET_errSuccess == (m_last_error = JetRollback(m_jses, grbit)); }

	private:
		ese::jet &m_ese;
		JET_SESID m_jses;
		JET_ERR m_last_error;
	};
	// ========================================================================

	inline bool session::start()
	{
		m_last_error = ::JetBeginSession(m_ese.id(), &m_jses, 0, 0);
		if (m_last_error != JET_errSuccess)
		{
			m_jses = JET_sesidNil;
			return false;
		}// if

		return true;
	}

	inline bool session::stop()
	{
		if (m_jses == JET_sesidNil)
		{
			return true;
		} // if

		try { m_last_error = ::JetEndSession(m_jses, 0); }
		catch (...){}
		m_jses = JET_sesidNil;
		return (m_last_error == JET_errSuccess);
	}

} // namespace